﻿using System;
using Qiniu.Common;
using Qiniu.IO;
using Qiniu.IO.Model;
using Qiniu.Http;
using Qiniu.Util;
using d1Common;

namespace d1Project.Modules.Common.doStorage.Domain
{
    public class QiniuMgr
    {
        private  static QiniuMgr singleInstance = new QiniuMgr();
        public  static QiniuMgr Instance
        {
            get
            {
                return singleInstance;
            }
        }
        private string AK = null;
        private string SK = null;
        private string bucket = null;
        private string DNS = null;
        public QiniuMgr()
        {
            this.AK = doServices.Instance.DoConfig.readConfigStringValue(doStorageModule.ModuleIdDefine, "Qiniu", "AK", null);
            if (this.AK == null)
            {
                throw new Exception("配置文件中未定义Ak");
            }
            this.SK = doServices.Instance.DoConfig.readConfigStringValue(doStorageModule.ModuleIdDefine, "Qiniu", "SK", null);
            if (this.SK == null)
            {
                throw new Exception("配置文件中未定义SK");
            }
            this.DNS = doServices.Instance.DoConfig.readConfigStringValue(doStorageModule.ModuleIdDefine, "Qiniu", "DNS", null);
            if (this.DNS == null)
            {
                throw new Exception("配置文件中未定义bucket");
            }

            this.bucket = doServices.Instance.DoConfig.readConfigStringValue(doStorageModule.ModuleIdDefine, "Qiniu", "bucket", null);
            if (this.bucket == null)
            {
                throw new Exception("配置文件中未定义DNS");
            }
        }

        /// <summary>
        /// 文件流上传
        /// </summary>
        /// <param name="saveKeys">文件名</param>
        /// <param name="filePath">文件流</param>
        public HttpResult uploadByte(string saveKeys, byte[] data)
        {
            Config.AutoZone(AK, bucket, false);
            Mac mac = new Mac(AK, SK);
            string saveKey = saveKeys;
            PutPolicy putPolicy = new PutPolicy();
            // 如果需要设置为"覆盖"上传(如果云端已有同名文件则覆盖)，请使用 SCOPE = "BUCKET:KEY"
            putPolicy.Scope = bucket + ":" + saveKey;
            //putPolicy.Scope = bucket;
            // 上传策略有效期(对应于生成的凭证的有效期)          
            putPolicy.SetExpires(100000);
            string jstr = putPolicy.ToJsonString();
            string token = Auth.CreateUploadToken(mac, jstr);
            FormUploader fu = new FormUploader();
            HttpResult result = fu.UploadData(data, saveKey, token);
            return result;
        }
      
    }

   
}